﻿Ext.require([
    'BIM.store.Role',
    'Twi.Msg',
    'Twi.Tbar',
    'Twi.QuickAjax',
    'Twi.QuickGrid',
    'Twi.QuickWin',
    'BIM.store.Role',
    'BIM.store.Operation',
    'TAB.view.role.NewOrEditForm'
]);

Ext.onReady(function () {
    Ext.QuickTips.init();
    Ext.form.Field.prototype.msgTarget = 'side';
    twiSelf.init();
});

Twi.TAB.RoleManage = {
    Vars:
    {
        roleGrid: null,
        authorityWin: null,
        moduleTree: null,
        operationGrid: null,
        sltRoleID: null,
        roleMappingName: 'SM008'
    },

    init: function () {
        twiVars.roleGrid = twiSelf.Grid.createRoleGrid();
    }

    , Grid:
    {
        createRoleGrid: function () {
            var store = Ext.create("BIM.store.Role");
            store.load();
            store.on('load', function (s) {
                //解决grid.store.load()后，默认选择的行其实是load之前选择的脏数据
                var grid = twiVars.roleGrid;
                var lastSltRecord = grid.getSelectionModel().getLastSelected();
                if (lastSltRecord) {
                    grid.getSelectionModel().deselectAll();
                    var sltRecord = s.getById(lastSltRecord.getId());
                    if (sltRecord) {
                        grid.getSelectionModel().select(sltRecord);
                    }
                }
            });
            var actionItems = twiSelf.ActionItems.createRoleItems();
            var contextMenu = Ext.create('Ext.menu.Menu', {
                items: actionItems
            });
            var tbarQuery = Twi.Tbar.Query('名称：', twiSelf.Fn.Role.btnQuery);
            var grid = Ext.create("Twi.QuickGrid", {
                title: '角色',
                //forceFit:true,
                store: store,
                renderTo: 'roleGrid',
                dockedItems: [{
                    xtype: 'toolbar',
                    items: actionItems.concat('->', tbarQuery)
                }],
                viewConfig: {
                    stripeRows: true,
                    listeners: {
                        itemcontextmenu: function (view, rec, node, index, e) {
                            e.stopEvent();
                            contextMenu.showAt(e.getXY());
                            return false;
                        }
                    }
                },
                columns: [{ xtype: 'rownumberer', width: 30 },
                 {
                     header: '名称',
                     dataIndex: 'FNAME',
                     flex: 1
                 }, {
                     header: '排序',
                     dataIndex: 'FSORT',
                     flex: 1
                 }, {
                     header: '备注',
                     dataIndex: 'FREMARK',
                     flex: 2
                 }]
            });
            grid.on('itemclick', function (view, record) {
                twiVars.sltRoleID = record.data.FID;
            });
            grid.on('itemdblclick', function () {
                if (!this.dockedItems.items[2].items.items[2].disabled) {
                    this.dockedItems.items[2].items.items[2].handler();
                }
            });

            return grid;

        } //end createRoleGrid

        , createOperationGrid: function () {
            var store = Ext.create("BIM.store.Operation");
            store.proxy.extraParams = {
                cn: 'Authority',
                mn: 'TAB',
                mn2: 'GetOperationList',
                moduleName: '',
                roleID: ''
            };
            var actionItems = twiSelf.ActionItems.createOperationItems();
            var contextMenu = Ext.create('Ext.menu.Menu', {
                items: actionItems
            });
            var selModel = Ext.create('Ext.selection.CheckboxModel');
            var grid = Ext.create("Twi.QuickGrid", {
                store: store,
                selModel: selModel,
                dockedItems: [{
                    xtype: 'toolbar',
                    items: actionItems
                }],
                height: 400,
                viewConfig: {
                    stripeRows: true,
                    listeners: {
                        itemcontextmenu: function (view, rec, node, index, e) {
                            e.stopEvent();
                            contextMenu.showAt(e.getXY());
                            return false;
                        }
                    }
                },
                columns: [{ xtype: 'rownumberer', width: 30 },
                 {
                     header: '操作名称',
                     dataIndex: 'FTEXT',
                     flex: 1
                 }, {
                     header: '是否授权',
                     dataIndex: 'InAuthority',
                     flex: 1,
                     renderer: function (value) {
                         if (value == "1") {
                             return '<span style="color:blue">是</span>';
                         }
                         else if (value == "0") {
                             return "";
                         }
                         else {
                             return value;
                         }
                     }
                 }]
            });

            return grid;

        } //end createOperationGrid

    } //end Grid

    , Tree:
    {
        createModuleTree: function () {
            var store = Ext.create('Ext.data.TreeStore', {
                fields: ['text', 'level', 'children', 'leaf', 'id', 'parentid', 'code'],
                root: {
                    text: '功能模块树'
                }
            });
            store.load();
            var actionItems = [{
                text: '展开',
                tooltip: '全部展开',
                iconCls: 'ico_details',
                handler: function () {
                    twiVars.moduleTree.expandAll();
                }
            }, {
                text: '折叠',
                tooltip: '折叠',
                iconCls: 'ico_listItems',
                handler: function () {
                    twiVars.moduleTree.getRootNode().collapseChildren();
                }
            }, Twi.Tbar.Refresh(twiSelf.Fn.Module.btnRefresh)];
            var tree = Ext.create('Ext.tree.Panel', {
                store: store,
                height: 400,
                width: 230,
                rootVisible: true,
                autoScroll: true,
                useArrows: true,
                dockedItems: [{
                    xtype: 'toolbar',
                    dock: 'top',
                    items: actionItems
                }]
            });
            tree.on('itemclick', function (view, record, item, index, e, eOpts) {
                if (record.data.leaf) {
                    twiVars.operationGrid.store.proxy.extraParams.moduleName = record.data.id;
                    twiVars.operationGrid.store.proxy.extraParams.roleID = twiVars.sltRoleID;
                    twiVars.operationGrid.store.load();
                }
                else {
                    twiVars.operationGrid.store.removeAll();
                }
            });
            Twi.QuickAjax.Ajax({
                params: {
                    cn: 'Authority',
                    mn: 'TAB',
                    mn2: 'GetModuleTreeData'
                },
                success: function (twi) {
                    var root = {
                        text: '功能模块树',
                        children: twi.data
                    };
                    store.setRootNode(root);
                    //tree.expandAll();
                    twiVars.moduleTree.expandNode(twiVars.moduleTree.getRootNode());
                }
            });
            //tree.expandAll();
            return tree;
        } //end createModuleTree

    }//end Tree

    , ActionItems: {
        createRoleItems: function () {
            var items = [];
            items.push({
                text: '新增',
                iconCls: 'ico_add',
                handler: twiSelf.Fn.Role.btnNew
            }, '-', {
                text: '编辑',
                iconCls: 'ico_edit',
                handler: twiSelf.Fn.Role.btnEdit
            }, '-', {
                text: '删除',
                iconCls: 'ico_delete',
                handler: twiSelf.Fn.Role.btnDelete
            }, '-', {
                text: '刷新',
                iconCls: 'ico_refresh',
                handler: twiSelf.Fn.Role.btnRefresh
            }, '-', {
                text: '功能授权',
                iconCls: 'ico_group',
                handler: twiSelf.Fn.Role.btnAuthority
            });
            return items;
        } //end createRoleItems

        , createOperationItems: function () {
            var items = [];
            items.push({
                text: '新增权限',
                iconCls: 'ico_add',
                handler: twiSelf.Fn.Operation.btnSetRight
            }, '-', {
                text: '取消权限',
                iconCls: 'ico_del',
                handler: twiSelf.Fn.Operation.btnCancelRight
            }, '-', {
                text: '刷新',
                iconCls: 'ico_refresh',
                handler: twiSelf.Fn.Operation.btnRefresh
            });
            return items;

        } //end createOperationItems

    }//end ActionItems

    , Win: {
        createRoleWin: function () {
            var form = Ext.create('TAB.view.role.NewOrEditForm', { border: false });
            var win = Ext.create('Twi.QuickWin', {
                title: '窗口',
                width: 300,
                //x: 140,
                //y: 100,
                items: [form]
            });
            return { win: win,
                form: form
            }
        } //end createRoleWin

        , createAuthorityWin: function () {
            twiVars.moduleTree = twiSelf.Tree.createModuleTree();
            twiVars.operationGrid = twiSelf.Grid.createOperationGrid();
            var win = Ext.create('Ext.window.Window', {
                title: '窗口',
                width: 640,
                //x: 140,
                //y: 400,
                closeAction: 'hide',
                modal: true,
                layout: {
                    type: 'table',
                    columns: 2
                },
                items: [{
                    border: false,
                    margin: '5 1 2 5',
                    height: 400,
                    items: twiVars.moduleTree,
                    width: 230
                }, {
                    items: twiVars.operationGrid,
                    border: false,
                    margin: '5 2 2 1',
                    height: 400,
                    width: 385
                }],
                buttons: [{
                    text: '关闭',
                    handler: function () {
                        this.up('window').hide();
                    }
                }]
            });
            return { win: win,
                tree: twiVars.moduleTree,
                grid: twiVars.operationGrid
            }
        } //end createAuthorityWin

    } //end win
    , Fn:
    {
        Role:
        {
            newOrEditCommit: function (win, newOrEdit) {
                var form = win.form.form;
                var btnCommit = win.win.down('#btnSave');
                btnCommit.clearListeners();
                btnCommit.on('click', function () {
                    if (form.isValid()) {
                        btnCommit.disable();
                        var record = form.getValues();
                        var data = {
                            TableName: twiVars.roleMappingName,
                            NewOrEdit: newOrEdit,
                            Fields: record,
                            SortModel: {
                                SortField: 'FSort'
                            }
                        };
                        if ("Edit" == newOrEdit) {
                            data.Condition =
                            {
                                FID: record.FID
                            }
                            delete data.Fields.FID;
                        }

                        Twi.QuickAjax.Ajax({
                            loadMask: true,
                            maskTarget: win.win.getEl(),
                            params: {
                                cn: 'PageCommon',
                                mn: 'TAB',
                                mn2: 'NewOrEdit',
                                data: Ext.encode(data)
                            },
                            success: function (obj) {
                                win.win.close();
                                twiSelf.Vars.roleGrid.store.load();
                            }
                        });
                    }
                });
            } //end newOrEditCommit

            , btnNew: function () {
                var win = twiSelf.Win.createRoleWin();
                win.win.setTitle('新增角色');
                twiSelf.Fn.Role.newOrEditCommit(win, 'New');
                win.win.show();
            }
            , btnEdit: function () {
                var len = twiVars.roleGrid.selModel.selected.length;
                if (len > 0) {
                    var win = twiSelf.Win.createRoleWin();
                    win.win.setTitle('编辑角色');
                    var record = twiVars.roleGrid.selModel.selected.items[len - 1];
                    win.form.loadRecord(record);
                    twiSelf.Fn.Role.newOrEditCommit(win, 'Edit');
                    win.win.show();
                }
                else {
                    Twi.Msg.Info('温馨提示', '请选择一项进行编辑');
                }

            }
            , btnDelete: function () {
                var len = twiVars.roleGrid.selModel.selected.length;
                if (len > 0) {
                    Twi.Msg.Confirm(function () {
                        var record = twiVars.roleGrid.selModel.selected.items[len - 1];
                        Twi.QuickAjax.Ajax({
                            params: {
                                cn: 'PageCommon',
                                mn: 'TAB',
                                mn2: 'Delete',
                                tableName: twiVars.roleMappingName,
                                id: record.data.FID
                            },
                            success: function () {
                                twiVars.roleGrid.store.load();
                            }
                        });
                    },'警告','角色为系统权限重要支撑数据，在不是特别清楚系统逻辑的情况下，</br>不要轻易执行删除操作，否则容易引起系统错误！！！</br>删除后数据将不能恢复，是否继续执行？');

                }
                else {
                    Twi.Msg.Info('温馨提示', '请选择一项进行删除');
                }
            } //end btnDelete

            , btnRefresh: function () {
                Ext.ComponentQuery.query('#txtContent', twiVars.roleGrid)[0].setValue("");
                var data = {
                    TableName: twiVars.roleMappingName,
                    OrderFields: 'FSORT'
                };
                twiVars.roleGrid.store.proxy.extraParams.data = Ext.encode(data);
                twiVars.roleGrid.store.load();

            } //end btnRefresh

            , btnAuthority: function () {
                var len = twiVars.roleGrid.selModel.selected.length;
                if (len > 0) {
                    if (!twiVars.authorityWin) {
                        twiVars.authorityWin = twiSelf.Win.createAuthorityWin();
                    }
                    var win = twiVars.authorityWin;
                    var record = twiVars.roleGrid.selModel.selected.items[len - 1];
                    win.win.setTitle('功能授权:当前角色->' + record.data.FNAME);
                    win.win.show();
                }
                else {
                    Twi.Msg.Info('温馨提示', '请选择一项进行操作');
                }
            } //end btnAuthority

            , btnQuery: function () {
                var content = Ext.ComponentQuery.query('#txtContent', twiVars.roleGrid)[0].value;
                var data = {
                    TableName: twiVars.roleMappingName,
                    OrderFields: 'FSORT'
                };
                if (content) {
                    data.SimpleCondition = {
                        Field: "FName",
                        Value: content,
                        COperator: 'Like'
                    };
                }
                twiVars.roleGrid.store.proxy.extraParams.data = Ext.encode(data);
                twiVars.roleGrid.store.load();

            } //end btnQuery

        }//end Role

        , Module:
        {
            btnRefresh: function () {
                Twi.QuickAjax.Ajax({
                    params: {
                        cn: 'Authority',
                        mn: 'TAB',
                        mn2: 'GetModuleTreeData'
                    },
                    success: function (twi) {
                        var root = {
                            text: '功能模块树',
                            children: twi.data
                        };
                        twiVars.moduleTree.store.setRootNode(root);
                        //tree.expandAll();
                        twiVars.moduleTree.expandNode(twiVars.moduleTree.getRootNode());
                        twiVars.operationGrid.store.removeAll();
                    }
                });
            } //end btnRefresh
        }  //end module

        , Operation: {

            btnSetRight: function () {
                var len = twiVars.operationGrid.selModel.selected.length;
                if (len > 0) {
                    var IDs = [];
                    Ext.each(twiVars.operationGrid.selModel.selected.items, function (item, index, allItems) {
                        IDs.push(item.data.FID);
                    });
                    Twi.QuickAjax.Ajax({
                        params: {
                            cn: 'Authority',
                            mn: 'TAB',
                            mn2: 'SetRight',
                            roleID: twiVars.sltRoleID,
                            operationIDs: IDs.join(',')
                        },
                        success: function (obj) {
                            twiSelf.Vars.operationGrid.store.load();
                        }
                    });
                }
                else {
                    Twi.Msg.Info('温馨提示', '请选择一项进行操作');
                }

            } //end btnSetRight

            , btnCancelRight: function () {
                var len = twiVars.operationGrid.selModel.selected.length;
                if (len > 0) {
                    var IDs = [];
                    Ext.each(twiVars.operationGrid.selModel.selected.items, function (item, index, allItems) {
                        IDs.push(item.data.FID);
                    });
                    Twi.QuickAjax.Ajax({
                        params: {
                            cn: 'Authority',
                            mn: 'TAB',
                            mn2: 'CancelRight',
                            roleID: twiVars.sltRoleID,
                            operationIDs: IDs.join(',')
                        },
                        success: function (obj) {
                            twiSelf.Vars.operationGrid.store.load();
                        }
                    });
                }
                else {
                    Twi.Msg.Info('温馨提示', '请选择一项进行操作');
                }
            } //end btnCancelRight

            , btnRefresh: function () {

            } //end btnRefresh

        } //end Operation
    } //end Fn

};

var twiSelf = Twi.TAB.RoleManage;
var twiVars = twiSelf.Vars;